package com.example.partner.activity.find;

import static android.content.ContentValues.TAG;
import static com.example.partner.common.ConfigConstant.BASE_URL;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import android.Manifest;
import android.Manifest;


import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.partner.R;
import com.example.partner.adapter.find.ImageAdapter;
import com.example.partner.adapter.find.PostAdapter;
import com.example.partner.common.BaseResponse;
import com.example.partner.model.domain.Post;
import com.example.partner.model.request.PostAddRequest;
import com.example.partner.service.OssService;
import com.example.partner.service.PostService;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class PublishPostActivity extends Activity {

    private List<String> selectedImages;
    private List<String> imagesUrl = new ArrayList<>();
    private ImageAdapter imageAdapter;
    private EditText titleEditText;
    private EditText contentEditText;
    private RecyclerView recyclerView;
    private static final int REQUEST_CODE_IMAGE_PICKER = 100;
    private static final int REQUEST_CODE_PERMISSION = 101;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_publish_post);
        // 初始化视图
        titleEditText = findViewById(R.id.editText3);
        contentEditText = findViewById(R.id.add_content);
        // 初始化图片选择器
        Button pickImageButton = findViewById(R.id.pickImageButton);
        pickImageButton.setOnClickListener(v -> openImagePicker());
        // 初始化 RecyclerView 和适配器
        selectedImages = new ArrayList<>();
        recyclerView = findViewById(R.id.imageRecyclerView);
        imageAdapter = new ImageAdapter(this, selectedImages);
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        recyclerView.setAdapter(imageAdapter);
        // 处理发布按钮点击事件
        Button publishButton = findViewById(R.id.publishButton);
        publishButton.setOnClickListener(v -> publishPost());
    }

    private void openImagePicker() {
        checkStoragePermission();
        // 在这里启动图片选择器，并在选择完成后处理返回的结果
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");
        intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
        startActivityForResult(intent, REQUEST_CODE_IMAGE_PICKER);
    }

    private void publishPost() {
        // 在这里获取标题、内容等输入，并将其发布到服务器
        String title = titleEditText.getText().toString();
        String content = contentEditText.getText().toString();
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        PostService postService = retrofit.create(PostService.class);
        SharedPreferences sharedPreferences = getSharedPreferences("CurrentUser", MODE_PRIVATE);
        Long userId = sharedPreferences.getLong("userId", -1);
        PostAddRequest postAddRequest = new PostAddRequest();
        postAddRequest.setTitle(title);
        postAddRequest.setContent(content);
        postAddRequest.setUserId(userId);
        String urls = String.join(",", imagesUrl);
        postAddRequest.setAvatarUrl(urls);
        Call<BaseResponse<Long>> call = postService.savePost(postAddRequest);
        call.enqueue(new Callback<BaseResponse<Long>>() {
            @Override
            public void onResponse(Call<BaseResponse<Long>> call, Response<BaseResponse<Long>> response) {
                if (response.isSuccessful()) {
                    // 帖子发布成功，显示提示给用户
                    showSuccessMessage("帖子发布成功");
                    finish();
                } else {
                    // 处理错误情况
                    Log.d(TAG, "onResponse:上传帖子失败fail");
                }
            }
            @Override
            public void onFailure(Call<BaseResponse<Long>> call, Throwable t) {
                // 网络错误处理
                t.printStackTrace();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_IMAGE_PICKER && resultCode == RESULT_OK && data != null) {
            // 处理从图片选择器返回的结果
            handleImagePickerResult(data);
        }
    }
    private void checkStoragePermission() {
        // 检查是否有权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            // 如果没有权限，请求权限
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.READ_MEDIA_IMAGES},
                    REQUEST_CODE_PERMISSION);
        } else {
            // 如果已经有权限，可以执行你的操作
        }
    }
    // 处理权限请求结果
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == REQUEST_CODE_PERMISSION) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 用户授予了存储权限，执行你的操作

            } else {
//                 用户拒绝了权限请求，可以给出一个提示
                Toast.makeText(this, "需要存储权限才能选择图片", Toast.LENGTH_SHORT).show();
                // 用户拒绝了权限请求，可以给出一个更详细的解释
                if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
                    // 显示一个解释，说明为什么需要这个权限
                    showPermissionExplanationDialog();
                } else {
                    // 用户选择了“不再询问”，引导用户到应用设置中手动启用权限
                    showPermissionSettingsDialog();
                }

            }
        }
    }

    private void showPermissionExplanationDialog() {
        // 在这里显示一个对话框，解释为什么应用需要存储权限
        // 可以包含一个按钮，再次请求权限
        // 在这里显示一个对话框，解释为什么应用需要存储权限
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("权限请求")
                .setMessage("我们需要存储权限来选择图片，请授予该权限。")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 重新请求权限
                        checkStoragePermission();
                    }
                })
                .setNegativeButton("取消", null)
                .show();
    }

    private void showPermissionSettingsDialog() {
        // 在这里显示一个对话框，引导用户到应用设置中启用权限
        // 可以包含一个按钮，点击按钮打开应用设置页面
        // 在这里显示一个对话框，引导用户到应用设置中启用权限
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("权限被拒绝")
                .setMessage("您已拒绝存储权限，请到应用设置中手动启用。")
                .setPositiveButton("去设置", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 打开应用设置页面
                        openAppSettings();
                    }
                })
                .setNegativeButton("取消", null)
                .show();
    }
    private void openAppSettings() {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", getPackageName(), null);
        intent.setData(uri);
        startActivity(intent);
    }

    // 上传图片到服务器
    private void uploadImageToServer(File imageFile) {
        // 创建RequestBody
        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), imageFile);
        // 创建MultipartBody.Part，用于包装文件数据
        MultipartBody.Part filePart = MultipartBody.Part.createFormData("file", imageFile.getName(), requestFile);
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        OssService ossService = retrofit.create(OssService.class);
        // 构建请求
        Call<BaseResponse<String>> call = ossService.uploadOssFile(filePart);
        // 发送请求
        call.enqueue(new Callback<BaseResponse<String>>() {
            @Override
            public void onResponse(Call<BaseResponse<String>> call, Response<BaseResponse<String>> response) {
                if (response.isSuccessful()) {
                    // 处理成功响应
                    imagesUrl.add(response.body().getData());
                    System.out.println("添加成功");
                } else {
                    // 处理错误响应
                    System.out.println("上传图片失败");
                    Log.d(TAG, "onResponse: upload fail");
                }
            }
            @Override
            public void onFailure(Call<BaseResponse<String>> call, Throwable t) {
                t.printStackTrace();                // 处理请求失败
                System.out.println("上传图片网络请求失败");
            }
        });
    }

    // 获取文件的实际路径
    private String getRealPathFromUri(Uri uri) {
        String[] projection = {MediaStore.Images.Media.DATA};
        Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
        if (cursor == null) return null;
        int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        String filePath = cursor.getString(columnIndex);
        cursor.close();
        return filePath;
    }

    //显示选择的图片
    private void handleImagePickerResult(Intent data) {
        if (data.getClipData() != null) {
            // 处理多张图片的情况
            int count = data.getClipData().getItemCount();
            for (int i = 0; i < count; i++) {
                Uri imageUri = data.getClipData().getItemAt(i).getUri();
                // 4. 将Uri转换为文件路径
                String filePath = getRealPathFromUri(imageUri);
                // 5. 创建Multipart请求并上传文件
                if (filePath != null) {
                    File imageFile = new File(filePath);
                    uploadImageToServer(imageFile);
                }
                selectedImages.add(imageUri.toString());
            }
        } else if (data.getData() != null) {
            // 处理单张图片的情况
            Uri imageUri = data.getData();
            // 4. 将Uri转换为文件路径
            String filePath = getRealPathFromUri(imageUri);
            // 5. 创建Multipart请求并上传文件
            if (filePath != null) {
                File imageFile = new File(filePath);
                uploadImageToServer(imageFile);
            }
            selectedImages.add(imageUri.toString());
        }
        // 通知适配器更新数据
        imageAdapter.notifyDataSetChanged();
    }
    private void showSuccessMessage(String message) {
        Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
    }


}
